﻿using System;
using System.Data;
using System.Data.Objects.DataClasses;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Markup;
using System.Xml;
using Dispatcher.Extensions;
using Dispatcher.Views;

namespace Dispatcher.Helpers
{
    /// <summary>
    /// List View Columns Helper.
    /// </summary>
    internal class ListViewColumnsHelper
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ListViewColumnsHelper"/> class.
        /// </summary>
        /// <param name="listView">The list view.</param>
        public ListViewColumnsHelper(CommonListView listView)
        {
            ListView = listView;
        }

        /// <summary>
        /// Gets the list view.
        /// </summary>
        public CommonListView ListView { get; private set; }

        /// <summary>
        /// Generates the column.
        /// </summary>
        /// <param name="dataGrid">The data grid.</param>
        /// <param name="e">The <see cref="System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs"/> instance containing the event data.</param>
        public void GenerateColumn(DataGrid dataGrid, DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.PropertyType == typeof(EntityKey) || e.PropertyType.BaseType == typeof(EntityReference))
            {
                e.Cancel = true;
            }

            if (e.PropertyName == "Id")
            {
                e.Column.IsReadOnly = true;
            }

            if (e.PropertyType == typeof(DateTime) && !e.PropertyName.Contains("Time"))
            {
                var cellTemplate = new DataTemplate();
                var textBlock = new FrameworkElementFactory(typeof(TextBlock));
                var binding1 = new Binding(e.PropertyName) { StringFormat = "dd.MM.yyyy" };
                textBlock.SetBinding(TextBlock.TextProperty, binding1);
                cellTemplate.VisualTree = textBlock;

                var dataTemplateXaml =
                    @"
                <DataTemplate
                xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
                xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
                    <Grid FocusManager.FocusedElement=""{Binding ElementName=BirthdayPicker}"">
                        <DatePicker Name=""BirthdayPicker"" 
                                    SelectedDate=""{Binding Path=" +
                    e.PropertyName +
                    @",
                                                            ValidatesOnExceptions=true, 
                                                            NotifyOnValidationError=true}""/>
                       </Grid>
                </DataTemplate>";

                var stringReader = new StringReader(dataTemplateXaml);
                var xmlReader = XmlReader.Create(stringReader);
                var cellEditingTemplate = (DataTemplate)XamlReader.Load(xmlReader);

                var column = new DataGridTemplateColumn
                {
                    Header = e.PropertyName,
                    CellTemplate = cellTemplate,
                    CellEditingTemplate = cellEditingTemplate,
                };

                e.Column = column;

                if (e.PropertyName == "Birthday")
                {
                    var ageColumn = new DataGridTextColumn
                        {
                            IsReadOnly = true,
                            Header = "Age",
                            Binding =
                                new Binding(e.PropertyName) { Converter = ConverterContainer.BirthdayToAgeConverter },
                        };

                    dataGrid.Columns.Add(column);
                    dataGrid.Columns.Add(ageColumn);
                    e.Cancel = true;
                }
            }

            if (e.PropertyType.BaseType == typeof(EntityObject))
            {
                var items = MainWindow.Model.ModelContainer.GetObjectSet(e.PropertyType);
                var column = new DataGridComboBoxColumn
                {
                    Header = e.PropertyName,
                    ItemsSource = items,
                    SelectedItemBinding = new Binding(e.PropertyName) { Mode = BindingMode.TwoWay },
                };
                e.Column = column;
            }

            if (e.PropertyType.BaseType != null && (e.PropertyType.BaseType == typeof(RelatedEnd)))
            {
                e.Column = new DataGridTextColumn
                    {
                        Binding = new Binding(e.PropertyName) { Converter = ConverterContainer.LazyLoadConverter },
                        Header = e.PropertyName,
                        IsReadOnly = true,
                        CellStyle = (Style)ListView.Resources["DataGridClickedCellStyle"],
                    };
            }

            ListView.ColumnPropertyRelation.Add(e.Column, e);
        }
    }
}
